import { useState } from 'react';
import { Link } from 'react-router-dom';
import { Search, Filter, Calendar, PenTool, Eye, Tag, FileText } from 'lucide-react';
import { useDiaryStore } from '../store/diaryStore';
import { TagBadge } from '../components/TagBadge';
import { format } from 'date-fns';

const moods = [
  { value: '', label: 'All Moods' },
  { value: 'happy', label: '😊 Happy' },
  { value: 'sad', label: '😢 Sad' },
  { value: 'excited', label: '🤩 Excited' },
  { value: 'calm', label: '😌 Calm' },
  { value: 'anxious', label: '😰 Anxious' },
  { value: 'grateful', label: '🙏 Grateful' },
  { value: 'thoughtful', label: '🤔 Thoughtful' },
  { value: 'energetic', label: '⚡ Energetic' },
];

export default function EntryList() {
  const { 
    entries, 
    searchQuery, 
    selectedMood,
    selectedTags,
    dateRange,
    setSearchQuery, 
    setSelectedMood,
    toggleTag,
    setDateRange,
    getFilteredEntries,
    getPopularTags,
    getTemplateById
  } = useDiaryStore();
  
  const [showFilters, setShowFilters] = useState(false);
  const [localSearchQuery, setLocalSearchQuery] = useState(searchQuery);
  const [startDate, setStartDate] = useState(dateRange?.start || '');
  const [endDate, setEndDate] = useState(dateRange?.end || '');
  
  const popularTags = getPopularTags(8);
  
  const filteredEntries = getFilteredEntries();
  
  const handleSearch = (query: string) => {
    setLocalSearchQuery(query);
    setSearchQuery(query);
  };
  
  const handleMoodFilter = (mood: string) => {
    setSelectedMood(mood);
  };
  
  const handleDateRangeFilter = () => {
    if (startDate && endDate) {
      setDateRange({ start: startDate, end: endDate });
    } else {
      setDateRange(null);
    }
  };
  
  const clearFilters = () => {
    setSearchQuery('');
    setLocalSearchQuery('');
    setSelectedMood('');
    useDiaryStore.getState().setSelectedTags([]);
    setDateRange(null);
    setStartDate('');
    setEndDate('');
  };
  
  const formatEntryDate = (dateString: string) => {
    try {
      return format(new Date(dateString), 'MMM dd, yyyy');
    } catch {
      return dateString;
    }
  };
  
  const truncateContent = (content: string, maxLength: number = 150) => {
    const textContent = content.replace(/<[^>]*>/g, ''); // Remove HTML tags
    return textContent.length > maxLength 
      ? textContent.substring(0, maxLength) + '...'
      : textContent;
  };
  
  const getMoodEmoji = (mood: string) => {
    const moodData = moods.find(m => m.value === mood);
    return moodData?.label.split(' ')[0] || '📝';
  };

  return (
    <div className="max-w-6xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-2xl font-inter font-bold text-forest-green">
            All Entries
          </h1>
          <p className="text-warm-gray mt-1">
            {filteredEntries.length} {filteredEntries.length === 1 ? 'entry' : 'entries'} found
          </p>
        </div>
        
        <Link to="/write" className="btn-primary flex items-center gap-2">
          <PenTool size={16} />
          New Entry
        </Link>
      </div>
      
      {/* Search and Filters */}
      <div className="card mb-8">
        {/* Search Bar */}
        <div className="relative mb-4">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-warm-gray w-5 h-5" />
          <input
            type="text"
            placeholder="Search entries by title or content..."
            value={localSearchQuery}
            onChange={(e) => handleSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-3 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-sage focus:border-transparent"
          />
        </div>
        
        {/* Filter Toggle */}
        <div className="flex items-center justify-between">
          <button
            onClick={() => setShowFilters(!showFilters)}
            className="flex items-center gap-2 text-sage hover:text-forest-green transition-colors"
          >
            <Filter size={16} />
            {showFilters ? 'Hide Filters' : 'Show Filters'}
          </button>
          
          {(searchQuery || selectedMood || selectedTags.length > 0 || dateRange) && (
            <button
              onClick={clearFilters}
              className="text-sm text-warm-gray hover:text-forest-green transition-colors"
            >
              Clear all filters
            </button>
          )}
        </div>
        
        {/* Filters Panel */}
        {showFilters && (
          <div className="mt-4 pt-4 border-t border-gray-200 space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {/* Mood Filter */}
              <div>
                <label className="block text-sm font-medium text-warm-gray mb-2">
                  Filter by Mood
                </label>
                <select
                  value={selectedMood}
                  onChange={(e) => handleMoodFilter(e.target.value)}
                  className="input-field"
                >
                  {moods.map((mood) => (
                    <option key={mood.value} value={mood.value}>
                      {mood.label}
                    </option>
                  ))}
                </select>
              </div>
              
              {/* Date Range Filter */}
              <div>
                <label className="block text-sm font-medium text-warm-gray mb-2">
                  From Date
                </label>
                <input
                  type="date"
                  value={startDate}
                  onChange={(e) => setStartDate(e.target.value)}
                  className="input-field"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium text-warm-gray mb-2">
                  To Date
                </label>
                <div className="flex gap-2">
                  <input
                    type="date"
                    value={endDate}
                    onChange={(e) => setEndDate(e.target.value)}
                    className="input-field flex-1"
                  />
                  <button
                    onClick={handleDateRangeFilter}
                    className="btn-secondary px-3"
                    disabled={!startDate || !endDate}
                  >
                    Apply
                  </button>
                </div>
              </div>
            </div>
            
            {/* Tag Filters */}
            <div>
              <label className="block text-sm font-medium text-warm-gray mb-2">
                <Tag className="inline w-4 h-4 mr-1" />
                Filter by Tags
              </label>
              {selectedTags.length > 0 && (
                <div className="mb-3">
                  <p className="text-xs text-sage mb-2">Selected tags:</p>
                  <div className="flex flex-wrap gap-2">
                    {selectedTags.map((tag) => (
                      <TagBadge
                        key={tag}
                        tag={tag}
                        onRemove={() => toggleTag(tag)}
                        size="sm"
                      />
                    ))}
                  </div>
                </div>
              )}
              {popularTags.length > 0 && (
                <div>
                  <p className="text-xs text-sage mb-2">Popular tags:</p>
                  <div className="flex flex-wrap gap-2">
                    {popularTags.map(({ tag, count }) => (
                      <TagBadge
                        key={tag}
                        tag={`${tag} (${count})`}
                        onClick={() => toggleTag(tag)}
                        interactive
                        size="sm"
                      />
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
      
      {/* Entries List */}
      {filteredEntries.length === 0 ? (
        <div className="card text-center py-12">
          {entries.length === 0 ? (
            <>
              <PenTool className="w-16 h-16 text-sage mx-auto mb-4" />
              <h3 className="text-xl font-inter font-semibold text-forest-green mb-2">
                No entries yet
              </h3>
              <p className="text-warm-gray mb-6">
                Start your journaling journey by writing your first entry.
              </p>
              <Link to="/write" className="btn-primary">
                Write Your First Entry
              </Link>
            </>
          ) : (
            <>
              <Search className="w-16 h-16 text-sage mx-auto mb-4" />
              <h3 className="text-xl font-inter font-semibold text-forest-green mb-2">
                No entries found
              </h3>
              <p className="text-warm-gray mb-6">
                Try adjusting your search terms or filters.
              </p>
              <button onClick={clearFilters} className="btn-secondary">
                Clear Filters
              </button>
            </>
          )}
        </div>
      ) : (
        <div className="space-y-4">
          {filteredEntries.map((entry) => (
            <div key={entry.id} className="card hover:shadow-md transition-shadow duration-200">
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-2">
                    <span className="text-2xl">{getMoodEmoji(entry.mood)}</span>
                    <div>
                      <h3 className="text-lg font-inter font-semibold text-forest-green">
                        {entry.title || 'Untitled Entry'}
                      </h3>
                      <div className="flex items-center gap-4 text-sm text-sage">
                        <span className="flex items-center gap-1">
                          <Calendar size={14} />
                          {formatEntryDate(entry.date)}
                        </span>
                        {entry.mood && (
                          <span>Mood: {entry.mood}</span>
                        )}
                        {entry.templateId && (() => {
                          const template = getTemplateById(entry.templateId);
                          return template ? (
                            <span className="flex items-center gap-1">
                              <FileText size={14} />
                              <span className="text-forest-green font-medium">{template.name}</span>
                            </span>
                          ) : null;
                        })()}
                      </div>
                    </div>
                  </div>
                  
                  {entry.tags && entry.tags.length > 0 && (
                    <div className="mb-3">
                      <div className="flex flex-wrap gap-2">
                        {entry.tags.slice(0, 3).map((tag) => (
                          <TagBadge
                            key={tag}
                            tag={tag}
                            size="sm"
                            onClick={() => toggleTag(tag)}
                            interactive
                          />
                        ))}
                        {entry.tags.length > 3 && (
                          <span className="text-xs text-sage px-2 py-1">
                            +{entry.tags.length - 3} more
                          </span>
                        )}
                      </div>
                    </div>
                  )}
                  
                  <p className="text-warm-gray mb-4 leading-relaxed">
                    {truncateContent(entry.content)}
                  </p>
                  
                  <div className="flex items-center gap-3">
                    <Link
                      to={`/entry/${entry.id}`}
                      className="flex items-center gap-2 text-sage hover:text-forest-green transition-colors"
                    >
                      <Eye size={16} />
                      Read More
                    </Link>
                    
                    <Link
                      to={`/write/${entry.id}`}
                      className="flex items-center gap-2 text-sage hover:text-forest-green transition-colors"
                    >
                      <PenTool size={16} />
                      Edit
                    </Link>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}